package com.gmzg.gmzgoffice;

import android.accessibilityservice.AccessibilityService;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.test.mock.MockApplication;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;

import java.lang.ref.WeakReference;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText mEditTextName;
    private EditText mEditTextPwd;
    private Button mButtonLogin;
    private Button mButtonSignUP;
    private ProgressBar mProgressBar;
    private InputMethodManager inputMethodManager;
    // 定义一个变量，来标识是否退出
    private static boolean isExit = false;

    private static Handler mBackPressedHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };
    @Override
    public void onBackPressed() {
        if (!isExit){
            isExit = true;
            Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
            mBackPressedHandler.sendEmptyMessageDelayed(889,2000);
        }else{
            finish();
        }
    }


    private Handler mHandler = new MyHandler(this);
    private static class MyHandler extends Handler {
        WeakReference<Activity> mActivityReference;

        public MyHandler(LoginActivity activity) {
            mActivityReference=new WeakReference<Activity> (activity);
        }
        @Override
        public void handleMessage(Message msg) {
            int what = msg.what;
            final LoginActivity context =  (LoginActivity)mActivityReference.get();
            switch (what) {
                case 999:
                    Toast.makeText(context, "登录成功", Toast.LENGTH_SHORT).show();

                    Intent intent = new Intent(context, MainActivity.class);
                    String currentUser = EMClient.getInstance().getCurrentUser();
                    SharedPreferences sp = context.getSharedPreferences("userInfo", MODE_PRIVATE);
                    SharedPreferences.Editor edit = sp.edit();
                    edit.putString("user", currentUser);
                    edit.apply();
                    ((GMZGApplication) context.getApplication()).setUserName(currentUser);
                    context.startActivity(intent);

                    context.finish();
                    break;
                case 100://登陆失败
                    context.mProgressBar.setVisibility(View.INVISIBLE);
                    Object obj = msg.obj;
                    if (obj!=null){
                        if (obj instanceof String) {
                            Toast.makeText(context, ((String) obj), Toast.LENGTH_SHORT).show();
                        }
                    }

                    break;
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
        inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        mButtonLogin.setOnClickListener(this);
        mButtonSignUP.setOnClickListener(this);
    }

    public void initView() {
        mEditTextName = (EditText) findViewById(R.id.login_user_name);
        mEditTextPwd = (EditText) findViewById(R.id.login_user_pwd);
        mButtonLogin = (Button) findViewById(R.id.login_confirm_button);
        mButtonSignUP = ((Button) findViewById(R.id.login_sign_up_button));
        mProgressBar = ((ProgressBar) findViewById(R.id.login_progress_bar));
    }

    //登录事件
    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.login_confirm_button:
                //隐藏软键盘
                if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
                    if (getCurrentFocus() != null)
                        inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                                InputMethodManager.HIDE_NOT_ALWAYS);
                }
                //set progress bar visible
                mProgressBar.setVisibility(View.VISIBLE);
                String userName = mEditTextName.getText().toString().trim();
                String userPwd = mEditTextPwd.getText().toString().trim();
                if (userName.length() > 0 && userPwd.length() > 0) {
                    EMClient.getInstance().logout(true);
                    EMClient.getInstance().login(userName, userPwd, new EMCallBack() {
                        @Override
                        public void onSuccess() {
                            // TODO: 环信登陆不判断密码，需要手动判断bomb云数据库的用户表信息，再进行登陆，如果密码不匹配，要异步注销刚在环信上登陆的用户
                            EMClient emClient = EMClient.getInstance();
                            emClient.groupManager().loadAllGroups(); // 内部加载所有的组信息，加载完成之后，可以直接获取
                            emClient.chatManager().loadAllConversations(); // 加载所有的会话
                            Message message = mHandler.obtainMessage(999);
                            mHandler.sendMessage(message);

                        }

                        @Override
                        public void onError(int i, String s) {
                            // 登陆失败处理
                            Message message = mHandler.obtainMessage(100);
                            message.arg1=i;
                            message.obj=s;
                            mHandler.sendMessage(message);
                        }

                        @Override
                        public void onProgress(int i, String s) {

                        }
                    });
                }
                break;
            case R.id.login_sign_up_button:
                mProgressBar.setVisibility(View.INVISIBLE);
                mEditTextName.setText("");
                mEditTextPwd.setText("");
                Intent intent = new Intent(this, SignUpActivity.class);
                startActivity(intent);
                finish();
                break;
        }

    }


}
